<template>
  <div class="com-container">
    <div class="com-chart" ref="rank_ref"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {
      allData: [],
      chartInstance: null,
      startVal: 0,
      endVal: 9,
      timer: null,
    };
  },

  created() {
    window.addEventListener('resize', this.screenAdapter);
    // 注册回调函数
    this.$socket.registerCallBack('rankData', this.getData);
  },

  mounted() {
    this.initChart();
    // this.getData();
    this.$socket.send({
      action: 'getData',
      socketType: 'rankData',
      chartName: 'rank',
      value: '',
    });
    this.screenAdapter();
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.screenAdapter);
    clearInterval(this.timer);

    this.$socket.unRegisterCallBack('rankData');
  },

  methods: {
    // init chart
    async initChart() {
      this.chartInstance = this.$echarts.init(
        this.$refs['rank_ref'],
        this.theme
      );
      // handle fixed options
      const initOption = {
        title: {
          text: '‖ 地区销售排行',
          left: 20,
          top: 20,
        },
        xAxis: {
          type: 'category',
        },
        yAxis: {
          type: 'value',
        },
        grid: {
          top: '40%',
          left: '5%',
          right: '5%',
          bottom: '5%',
          containLabel: true, // 距离是包含坐标轴上的文字
        },
        tooltip: {
          show: true,
        },
        series: [
          {
            type: 'bar',
          },
        ],
      };
      this.chartInstance.setOption(initOption);
      this.chartInstance.on('mouseout', () => {
        this.startInterval();
      });
      this.chartInstance.on('mouseover', () => {
        clearInterval(this.timer);
      });
    },

    async getData() {
      const { data } = await this.$http.get('rank');
      this.allData = data;
      this.allData.sort((a, b) => b.value - a.value);
      this.updateChart();
      this.startInterval();
    },

    updateChart() {
      const colorArr = [
        ['#0BA82C', '#4FF778'],
        ['#2E72BF', '#23E5E5'],
        ['#5052EE', '#AB6EE5'],
      ];
      const provinceArr = this.allData.map((item) => item.name);
      const seriesArr = this.allData.map((item) => item.value);
      // console.log(seriesArr)
      // handle data options
      const dataOption = {
        xAxis: {
          data: provinceArr,
        },
        dataZoom: {
          show: false,
          startValue: this.startVal,
          endValue: this.endVal,
        },
        series: [
          {
            data: seriesArr,
            itemStyle: {
              color: (arg) => {
                let targetColorArr = null;
                if (arg.value > 300) {
                  targetColorArr = colorArr[0];
                } else if (arg.value > 200) {
                  targetColorArr = colorArr[1];
                } else {
                  targetColorArr = colorArr[2];
                }
                return new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: targetColorArr[0],
                  },
                  {
                    offset: 1,
                    color: targetColorArr[1],
                  },
                ]);
              },
            },
          },
        ],
      };

      this.chartInstance.setOption(dataOption);
    },

    screenAdapter() {
      const titleFontsize = (this.$refs['rank_ref'].offsetWidth / 100) * 3.6;
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontsize,
          },
        },
        series: [
          {
            barWidth: titleFontsize,
            itemStyle: {
              barBorderRadius: [titleFontsize / 2, titleFontsize / 2, 0, 0],
            },
          },
        ],
      };
      this.chartInstance.setOption(adapterOption);
      this.chartInstance.resize();
    },

    startInterval() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.timer = setInterval(() => {
        this.startVal++;
        this.endVal++;
        if (this.endVal > this.allData.length - 1) {
          this.startVal = 0;
          this.endVal = 9;
        }

        this.updateChart();
      }, 1500);
    },
  },
  computed: {
    ...mapState(['theme']),
  },
  watch: {
    theme() {
      console.log('主题切换了');
      this.chartInstance.dispose(); // 销毁当前的图表
      this.initChart(); // 重新以最新的主题名称初始化图表对象
      this.screenAdapter(); // 完成屏幕的适配
      this.updateChart(); // 更新图表的展示
    },
  },
};
</script>

<style scoped lang="scss"></style>
